<?php
/**
 * 分类验证 - 管理后台
 *
 * @author birdy <freebirdy@foxmail.com>
 * @link http://www.aiyuangong.com
 */

namespace app\admin\validate;

use think\Validate;
use think\Db;

class Type extends Validate
{
    protected $rule = [
        "name|分类名称"  => "require",
        "pid|父级"   => "require|checkPid:1",
        "tag|标识"   => "require|checkTag:1",
        "sort|排序"   => "require",
        "status|状态" => "require",
    ];
    
    protected $scene = [
        'add'  =>  ['name', 'pid', 'tag', 'sort', 'status'],
        'edit' =>  ['name', 'tag', 'sort', 'status']
    ];

    /**
     * 验证父结点是否存在
     */
    protected function checkPid($value, $rule, $data)
    {
        if (isset($data['pid']) && $data['pid'] > 0) {
            $where = [];
            $where['id']       = $data['pid'];
            $where['status']   = 1;
            $where['isdelete'] = 0;
            $item = Db::name("Type")->where($where)->count();
            if (!$item) {
                return  "父节点不存在";
            }
        } else {
            $data['pid'] = 0;
        }

        return true;
    }

    /**
     * 验证父结点及非空Tag标识是否同级唯一
     */
    protected function checkTag($value, $rule, $data)
    {        
        if (!empty($data['tag'])) {
            $where = [];
            if (!empty($data['id']) && $this->currentScene == "edit") {
                $item = Db::name("Type")->find($data['id']);
                $where['pid'] = $item['pid'];
                $where['id']  = ['neq', $data['id']];
            } else {
                $where['pid'] = $data['pid'];
            }
            $where['tag']      = $data['tag'];
            $item = Db::name("Type")->where($where)->count();
            if ($item) {
                return  "同级标识（".$data['tag']."）已经存在";
            }
        }

        return true;
    }
}